package net.wanho.config;

import net.wanho.shiro.ShiroRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2023-10-11 16:02
 * Description：<描述>
 */
@Configuration
public class ShiroConfig {

    /**
     * ShiroFilter，对资源进行过滤处理
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 设置url过滤规则
        Map<String,String> map = new LinkedHashMap<>(); // LinkedHashMap是有序的
        map.put("/login.jsp","anon");
        map.put("/register.jsp","anon");
        map.put("/user/login","anon");
        map.put("/user/logout","anon");
        map.put("/user/register","anon");
        map.put("/*","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        // 设置默认登录的url
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");

        return shiroFilterFactoryBean;
    }

    /**
     * 创建安全管理器
     */
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置Realm
        securityManager.setRealm(realm);

        return securityManager;
    }

    /**
     * 创建自定义Realm
     */
    @Bean
    public Realm getRealm(){
        ShiroRealm realm = new ShiroRealm();

        // 创建凭证匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5"); // 设置加密算法
        matcher.setHashIterations(1024); // 设置加密次数

        // 设置凭证匹配器
        realm.setCredentialsMatcher(matcher);
        return realm;
    }

}
